package com.bodacn.keypoint;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

public class StyleNoActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    private final int MSG_DepartOver=1001;
    private final int MSG_OrderOver =1002;
    private final int MSG_POOver =1003;
    private final int MSG_DetailOver=1004;
    private final int MSG_FocusDefaultItem =1005;
    private final int MSG_FactoryOver =1006;
    Button btn_Refresh,btn_Affirm,btn_Return,btn_SelectWorkShop;
    GridView departGrid,poGrid;
    ListView orderList,detailList;
    JSONArray departJson,orderJson,poJson,detailJson,factoryJson,headJSON,selectItemJson;
    String STORE_NAME = "Settings";
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    String selDepart="",selDepartNo="",selOrderNo="",selStyleNo="",selStyleSort="",selPO="",selColor="",selSize="",selImageFile="",selPSXX="",selManuDepartNo="",selManuDepart="";
    String selFactory="";
    String FormType="REPAIR";
    Boolean ViewFactory=false;
    View tmpItemView;
    int tmpItemIndex=-1;
    int DateNum=10;
    LinearLayout templetlisthead;
    ListView selectTempletList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_styleno);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        selDepart=paramBundle.getString("selDepart");
        selDepartNo=paramBundle.getString("selDepartNo");
        FormType=paramBundle.getString("FormType");
        DateNum=paramBundle.getInt("DateNum");
        CPUID=paramBundle.getString("CPUID");
        ViewFactory=paramBundle.getBoolean("ViewFactory",ViewFactory);
        InitView();
        ((TextView)findViewById(R.id.txt_Depart)).setText(selDepart);
        ((TextView)findViewById(R.id.txt_DateRange)).setText("近"+DateNum+"天内合约");
        if (ViewFactory==true) ((Button)findViewById(R.id.btn_SelectWorkShop)).setVisibility(View.VISIBLE);
        else ((Button)findViewById(R.id.btn_SelectWorkShop)).setVisibility(View.GONE);
        hideBottomUIMenu();
        if (FormType.equals("IRON")==false){
            findViewById(R.id.item_TotalNum).setVisibility(View.GONE);
            findViewById(R.id.item_ReadyNum).setVisibility(View.GONE);
            findViewById(R.id.item_OwenNum).setVisibility(View.GONE);
            findViewById(R.id.lbl_PO).setVisibility(View.GONE);
            findViewById(R.id.txt_PO).setVisibility(View.GONE);
            findViewById(R.id.lbl_Size).setVisibility(View.GONE);
            findViewById(R.id.txt_Size).setVisibility(View.GONE);
            findViewById(R.id.poGrid).setVisibility(View.GONE);
            findViewById(R.id.poline).setVisibility(View.GONE);

        }
    }


    //初始化;
    public void InitView(){
        ((Button)findViewById(R.id.btn_UpDate)).setOnClickListener(this);
        ((Button)findViewById(R.id.btn_DownDate)).setOnClickListener(this);
        btn_SelectWorkShop=findViewById(R.id.btn_SelectWorkShop);
        btn_SelectWorkShop.setOnClickListener(this);
        btn_Refresh=findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
        btn_Affirm=findViewById(R.id.btn_Affirm);
        btn_Affirm.setOnClickListener(this);
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        departGrid=findViewById(R.id.departGrid);
        departGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    selDepartNo=departJson.optJSONObject(i).getString("DepartNo");
                    selDepart=departJson.optJSONObject(i).getString("DepartName");
                    ((TextView)findViewById(R.id.txt_Depart)).setText(selDepart);
                    selOrderNo="";
                    selStyleNo="";
                    selStyleSort="";
                    selPO="";
                    selColor="";
                    selSize="";
                    selPSXX="";
                    selImageFile="";
                    fillSelect();
                    GetOrder(selDepart);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        orderList=findViewById(R.id.orderList);
        orderList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    view.setSelected(true);
                    if (orderJson.optJSONObject(i).has("ManuDepartNo"))selManuDepartNo=orderJson.optJSONObject(i).getString("ManuDepartNo");
                    if (orderJson.optJSONObject(i).has("ManuDepart")) selManuDepart=orderJson.optJSONObject(i).getString("ManuDepart");
                    selOrderNo=orderJson.optJSONObject(i).getString("OrderNo");
                    selStyleNo=orderJson.optJSONObject(i).getString("StyleNo");
                    selStyleSort=orderJson.optJSONObject(i).getString("StyleSort");
                    selImageFile=orderJson.optJSONObject(i).getString("ImageFile");
                    selPO="";
                    selColor="";
                    selSize="";
                    selPSXX="";
                    fillSelect();
                    if (findViewById(R.id.poGrid).getVisibility()==View.VISIBLE) {
                        GetPO(selDepart, selOrderNo, selStyleNo, selStyleSort, selManuDepartNo);
                    } else{
                        GetDetail(selDepart,selOrderNo,selStyleNo,selStyleSort,"*",selManuDepartNo);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        poGrid=findViewById(R.id.poGrid);
        poGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    selPO=poJson.optJSONObject(i).getString("PO");
                    selColor="";
                    selSize="";
                    selPSXX="";
                    fillSelect();
                    GetDetail(selDepart,selOrderNo,selStyleNo,selStyleSort,selPO,selManuDepartNo);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        detailList=findViewById(R.id.colorsizeList);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    view.setSelected(true);
                    selColor=detailJson.optJSONObject(i).getString("Color");
                    selSize=detailJson.optJSONObject(i).getString("Size");
                    selPSXX=detailJson.optJSONObject(i).getString("PSXX");
                    fillSelect();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //填充选择数据
    private void fillSelect(){
        ((TextView)findViewById(R.id.txt_Depart)).setText(selDepart);
        ((TextView)findViewById(R.id.txt_OrderNo)).setText(selOrderNo);
        ((TextView)findViewById(R.id.txt_StyleNo)).setText(selStyleNo);
        ((TextView)findViewById(R.id.txt_StyleSort)).setText(selStyleSort);
        ((TextView)findViewById(R.id.txt_PO)).setText(selPO);
        ((TextView)findViewById(R.id.txt_Color)).setText(selColor);
        ((TextView)findViewById(R.id.txt_Size)).setText(selSize);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_Refresh:
                GetDepartData();
                GetOrder(selDepart);
                break;
            case R.id.btn_SelectWorkShop:
                GetFacotry();
                break;
            case R.id.btn_Affirm:
                if (FormType.equals("IRON")==false) {
                    selPO="*";
                    selSize="*";
                }
                if ((selDepartNo.length()>0)&&(selOrderNo.length()>0)&&(selColor.length()>0))
                {
                    //返回
                    Intent intent = new Intent();
                    intent.putExtra("selDepartNo",selDepartNo);
                    intent.putExtra("selDepart",selDepart);
                    intent.putExtra("selOrderNo",selOrderNo);
                    intent.putExtra("selStyleNo",selStyleNo);
                    intent.putExtra("selStyleSort",selStyleSort);
                    intent.putExtra("selPO",selPO);
                    intent.putExtra("selColor",selColor);
                    intent.putExtra("selSize",selSize);
                    intent.putExtra("selPSXX",selPSXX);
                    intent.putExtra("selManuDepartNo",selManuDepartNo);
                    intent.putExtra("selManuDepart",selManuDepart);
                    intent.putExtra("selImageFile",selImageFile);
                    setResult(1001,intent);
                    finish();
                } else {
                    Toast.makeText(this,"请选择合约及颜色尺码!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_Return:
                finish();
                break;
            case R.id.btn_UpDate:
                if (DateNum>10) DateNum=DateNum-10;
                ((TextView)findViewById(R.id.txt_DateRange)).setText("近"+DateNum+"天内合约");
                break;
            case R.id.btn_DownDate:
                DateNum=DateNum+10;
                ((TextView)findViewById(R.id.txt_DateRange)).setText("近"+DateNum+"天内合约");
                break;
            default:
                break;
        }
    }

    private void GetFacotry() {
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_GetFactory @DepartNo='" + curDepartNo + "',@FormType='" + FormType +"',@OPERTYPE='Factory',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    @Override
    protected void onResume() {
        super.onResume();
        GetDepartData();
    }

    //测算克重
    private void GetDepartData()
    {
        try {
            departJson=new JSONArray("[]");
            orderJson=new JSONArray("[]");
            poJson=new JSONArray("[]");
            detailJson=new JSONArray("[]");
            //显示明细数据
            OrderListAdapter orderListAdapter=new OrderListAdapter(getApplicationContext());
            orderList.setAdapter(orderListAdapter);
            //显示明细数据
            POGridAdapter poGridAdapter=new POGridAdapter(getApplicationContext());
            poGrid.setAdapter(poGridAdapter);
            //显示明细数据
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            detailList.setAdapter(detailListAdapter);
            tmpItemView =null;
            tmpItemIndex=-1;

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String paramFactory="NULL";
        if (btn_SelectWorkShop.getVisibility()==View.VISIBLE)  {
            if ((selFactory!=null)&&(selFactory.length()>0)) paramFactory=selFactory;
        }
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_GetDepart @Factory='"+paramFactory+"',@DepartNo='" + curDepartNo + "',@FormType='" + FormType + "',@DateNum="+DateNum+",@OPERTYPE='Depart',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //获取订单
    private void GetOrder(String paramDepart) {
        try {
            orderJson=new JSONArray("[]");
            poJson=new JSONArray("[]");
            detailJson=new JSONArray("[]");
            //显示明细数据
            OrderListAdapter orderListAdapter=new OrderListAdapter(getApplicationContext());
            orderList.setAdapter(orderListAdapter);
            //显示明细数据
            POGridAdapter poGridAdapter=new POGridAdapter(getApplicationContext());
            poGrid.setAdapter(poGridAdapter);
            //显示明细数据
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            detailList.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_GetOrder @Depart='" + paramDepart + "',@FormType='" + FormType + "',@DateNum="+DateNum+",@OPERTYPE='Order',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //获取明细
    private void GetPO(String paramDepart,String paramOrderNo,String paramStyleNo,String paramStyleSort,String paramManuDepartNo) {
        try {
            poJson=new JSONArray("[]");
            detailJson=new JSONArray("[]");
            //显示明细数据
            POGridAdapter poGridAdapter=new POGridAdapter(getApplicationContext());
            poGrid.setAdapter(poGridAdapter);
            //显示明细数据
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            detailList.setAdapter(detailListAdapter);
            //执行SQL过程
            String SqlComm = "Exec KeyPoint_GetPO @ManuDepartNo='"+paramManuDepartNo+"',@Depart='" + paramDepart + "',@OrderNo='" + paramOrderNo + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort
                    + "',@FormType='" + FormType + "',@DateNum="+DateNum+", @OPERTYPE='PO',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //获取明细
    private void GetDetail(String paramDepart,String paramOrderNo,String paramStyleNo,String paramStyleSort,String paramPO,String paramManuDepartNo) {
        try {
            detailJson=new JSONArray("[]");
            //显示明细数据
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            detailList.setAdapter(detailListAdapter);
            //执行SQL过程
            String SqlComm = "Exec KeyPoint_GetSize @ManuDepartNo='"+paramManuDepartNo+"',@Depart='" + paramDepart + "',@OrderNo='" + paramOrderNo + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort
                    + "',@PO='" + paramPO+ "',@FormType='" + FormType + "',@DateNum="+DateNum+", @OPERTYPE='ColorSize',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        String OPERTYPE="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType")==true) OPERTYPE=jsonArray.optJSONObject(0).getString("OperType");
                        if (OPERTYPE.toUpperCase().equals("DEPART")) {
                            departJson= jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DepartOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("ORDER")) {
                            orderJson=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_OrderOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("PO")) {
                            poJson=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_POOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("DETAIL")||OPERTYPE.toUpperCase().equals("COLORSIZE")) {
                            detailJson=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OPERTYPE.toUpperCase().equals("FACTORY")){
                            factoryJson=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_FactoryOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_DepartOver:
                    //创建列;
                    DepartGridAdapter departGridAdapter=new DepartGridAdapter(getApplicationContext());
                    departGrid.setAdapter(departGridAdapter);
                    break;
                case MSG_OrderOver:
                    //显示明细数据
                    OrderListAdapter orderListAdapter=new OrderListAdapter(getApplicationContext());
                    orderList.setAdapter(orderListAdapter);
                    break;
                case MSG_POOver:
                    //显示明细数据
                    POGridAdapter poGridAdapter=new POGridAdapter(getApplicationContext());
                    poGrid.setAdapter(poGridAdapter);
                    break;
                case MSG_DetailOver:
                    //显示明细数据
                    DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
                    detailList.setAdapter(detailListAdapter);
                    break;
                case MSG_FocusDefaultItem:
                    if ((tmpItemView!=null)&&(tmpItemIndex>-1)){
                        departGrid.requestFocusFromTouch();
                        departGrid.setSelection(tmpItemIndex);
                        departGrid.requestFocus(tmpItemIndex);
                        departGrid.performItemClick(departGrid.getChildAt(tmpItemIndex), tmpItemIndex, departGrid.getItemIdAtPosition(tmpItemIndex));
                    }
                    break;
                case MSG_FactoryOver:
                    showSelectFactory();
                    break;
                default:
                    break;
            }
        }
    };

    //显示工序选择
    private void showSelectFactory(){
        if (factoryJson==null){
            Toast.makeText(this,"没有工厂信息!",Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            headJSON=new JSONArray("[{\"TitleName\":\"DepartmentNo\",\"TitleText\":\"车间编号\",\"TxtSize\":18,\"TxtWidth\":120,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"Department\",\"TitleText\":\"车间名称\",\"TxtSize\":18,\"TxtWidth\":200,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="车间选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        selectItemJson=factoryJson;
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (selectItemJson.optJSONObject(position).has("Department")==true)
                        selFactory=selectItemJson.optJSONObject(position).getString("Department");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(this);
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selFactory.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            Toast.makeText(getApplicationContext(), "请点击要选择的内容！",Toast.LENGTH_SHORT).show();
                        } else{
                            btn_SelectWorkShop.setText(selFactory);
                            btn_SelectWorkShop.setBackgroundColor(getResources().getColor(R.color.skyblue));
                            GetDepartData();
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selFactory="";
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width = 500;
        params.height = 400 ;
        alterDialog.getWindow().setAttributes(params);
    }

    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return selectItemJson.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<selectItemJson.length())
                    return selectItemJson.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<selectItemJson.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (selectItemJson.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = selectItemJson.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (selectItemJson.optJSONObject(curPosition).has(TitleName)==true) tmpValue= selectItemJson.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }
    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    //订单表格适配器;
    public final class DepartGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DepartGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return departJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return departJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_styleno_departitem, null, false);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (departJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = departJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((departJson.optJSONObject(position).has("DepartNo") == true)&&(view.findViewById(R.id.item_DepartNo)!=null)) {
                    ((TextView) view.findViewById(R.id.item_DepartNo)).setText(departJson.optJSONObject(position).getString("DepartNo"));
                    //((TextView) view.findViewById(R.id.item_DepartNo)).setTextColor(color);
                }
                if ((departJson.optJSONObject(position).has("DepartName") == true)&&(view.findViewById(R.id.item_DepartName)!=null)) {
                    ((TextView) view.findViewById(R.id.item_DepartName)).setText(departJson.optJSONObject(position).getString("DepartName"));
                    //((TextView) view.findViewById(R.id.item_DepartName)).setTextColor(color);
                }

                if (departJson.optJSONObject(position).has("Selected")==true){
                    if (departJson.optJSONObject(position).getString("Selected").equals("YES")) {
                        //默认选中第0个，因为还没有确定界面，所以要延时选中;
                        if (tmpItemView == null) {
                            tmpItemView = view;
                            tmpItemIndex = position;
                            tmpItemView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d("msg", "tmpItemView.postDelayed");
                                    //刷新界面;
                                    Message msg = new Message();
                                    msg.what = MSG_FocusDefaultItem;
                                    handler.removeMessages(msg.what);
                                    handler.sendMessage(msg);
                                }
                            }, 200);
                        }
                    }
                } else {
                    if (selDepart.equals(departJson.optJSONObject(position).getString("DepartName"))) {
                        //默认选中第0个，因为还没有确定界面，所以要延时选中;
                        if (tmpItemView == null) {
                            tmpItemView = view;
                            tmpItemIndex = position;
                            tmpItemView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d("msg", "tmpItemView.postDelayed");
                                    //刷新界面;
                                    Message msg = new Message();
                                    msg.what = MSG_FocusDefaultItem;
                                    handler.removeMessages(msg.what);
                                    handler.sendMessage(msg);
                                }
                            }, 200);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DepartGridAdapter_position:"+position);
            return view;
        }
    }

    //订单表格适配器;
    public final class POGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public POGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return poJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return poJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_style_poitem, null, false);
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if ((poJson.optJSONObject(position).has("PO") == true)&&(view.findViewById(R.id.item_PO)!=null)) {
                    ((TextView) view.findViewById(R.id.item_PO)).setText(poJson.optJSONObject(position).getString("PO"));
                    //((TextView) view.findViewById(R.id.item_DepartNo)).setTextColor(color);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","POGridAdapter_position:"+position);
            return view;
        }
    }
    //订单表格适配器;
    public final class OrderListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public OrderListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return orderJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return orderJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_styleno_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (orderJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = orderJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((orderJson.optJSONObject(position).has("ManuDepart") == true)&&(view.findViewById(R.id.item_ManuDepart)!=null)) {
                    ((TextView) view.findViewById(R.id.item_ManuDepart)).setText(orderJson.optJSONObject(position).getString("ManuDepart"));
                    ((TextView) view.findViewById(R.id.item_ManuDepart)).setTextColor(color);
                }
                if ((orderJson.optJSONObject(position).has("OrderNo") == true)&&(view.findViewById(R.id.item_OrderNo)!=null)) {
                    ((TextView) view.findViewById(R.id.item_OrderNo)).setText(orderJson.optJSONObject(position).getString("OrderNo"));
                    ((TextView) view.findViewById(R.id.item_OrderNo)).setTextColor(color);
                }
                if ((orderJson.optJSONObject(position).has("StyleNo") == true)&&(view.findViewById(R.id.item_StyleNo)!=null)) {
                    ((TextView) view.findViewById(R.id.item_StyleNo)).setText(orderJson.optJSONObject(position).getString("StyleNo"));
                    ((TextView) view.findViewById(R.id.item_StyleNo)).setTextColor(color);
                }
                if ((orderJson.optJSONObject(position).has("StyleSort") == true)&&(view.findViewById(R.id.item_StyleSort)!=null)) {
                    ((TextView) view.findViewById(R.id.item_StyleSort)).setText(orderJson.optJSONObject(position).getString("StyleSort"));
                    ((TextView) view.findViewById(R.id.item_StyleSort)).setTextColor(color);
                }
                if (orderJson.optJSONObject(position).has("ImageFile") == true) selImageFile=orderJson.optJSONObject(position).getString("ImageFile");

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","OrderListAdapter_position:"+position);
            return view;
        }
    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_stylecolor_listhead, null, false);
            if  (FormType.equals("IRON")==false){
                view.findViewById(R.id.item_TotalNum).setVisibility(View.GONE);
                view.findViewById(R.id.item_ReadyNum).setVisibility(View.GONE);
                view.findViewById(R.id.item_OwenNum).setVisibility(View.GONE);
            }
            int pullVatListWidth=parent.getWidth();
            //view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                if ((detailJson.optJSONObject(position).has("PSXX") == true)&&(view.findViewById(R.id.item_PSXX)!=null)) {
                    ((TextView) view.findViewById(R.id.item_PSXX)).setText(detailJson.optJSONObject(position).getString("PSXX"));
                    ((TextView) view.findViewById(R.id.item_PSXX)).setTextColor(color);
                }

                if ((detailJson.optJSONObject(position).has("Color") == true)&&(view.findViewById(R.id.item_Color)!=null)) {
                    ((TextView) view.findViewById(R.id.item_Color)).setText(detailJson.optJSONObject(position).getString("Color"));
                    ((TextView) view.findViewById(R.id.item_Color)).setTextColor(color);
                }
                if ((detailJson.optJSONObject(position).has("Size") == true)&&(view.findViewById(R.id.item_Size)!=null)) {
                    ((TextView) view.findViewById(R.id.item_Size)).setText(detailJson.optJSONObject(position).getString("Size"));
                    ((TextView) view.findViewById(R.id.item_Size)).setTextColor(color);
                }
                if ((detailJson.optJSONObject(position).has("TotalNum") == true)&&(view.findViewById(R.id.item_TotalNum)!=null)) {
                    ((TextView) view.findViewById(R.id.item_TotalNum)).setText(detailJson.optJSONObject(position).getString("TotalNum"));
                    ((TextView) view.findViewById(R.id.item_TotalNum)).setTextColor(color);
                }
                if ((detailJson.optJSONObject(position).has("ReadyNum") == true)&&(view.findViewById(R.id.item_ReadyNum)!=null)) {
                    ((TextView) view.findViewById(R.id.item_ReadyNum)).setText(detailJson.optJSONObject(position).getString("ReadyNum"));
                    ((TextView) view.findViewById(R.id.item_ReadyNum)).setTextColor(color);
                }
                if ((detailJson.optJSONObject(position).has("OwenNum") == true)&&(view.findViewById(R.id.item_OwenNum)!=null)) {
                    ((TextView) view.findViewById(R.id.item_OwenNum)).setText(detailJson.optJSONObject(position).getString("OwenNum"));
                    ((TextView) view.findViewById(R.id.item_OwenNum)).setTextColor(color);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }


    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }


}